package cn.wuqingna.legendgem.util

import org.bukkit.entity.Player
import taboolib.module.configuration.util.asMap
import taboolib.platform.BukkitPlugin
import kotlin.random.Random


// 顶替taboolib 自带的info
fun info(vararg message: Any?): kotlin.Unit {
    message.filterNotNull().forEach {
        BukkitPlugin.getInstance().server.consoleSender.sendMessage(
            "§8[ §e${BukkitPlugin.getInstance().description.name} §8] §f${
                it.toString().replace("&", "§")
            }"
        )
    }
}

fun <T> org.bukkit.configuration.ConfigurationSection.mapListAs(path: String, transform: (Map<String, Any?>) -> T): MutableList<T> {
    return getMapList(path).map { transform(it.asMap()) }.toMutableList()
}

fun String.getStringRepeatNum(repeat: String): Int{
    var num = 0
    var str = this
    if (this.contains(repeat)) {
        str = str.replaceFirst(repeat, "")
        num++
    }

    if (num != 0) {
        num += str.getStringRepeatNum(repeat)
    }
    return num
}

fun String.isDouble(): Boolean{
    return try {
        this.toDouble()
        true
    } catch (e: NumberFormatException){
        false
    }
}

fun randomInt(random: Int): Boolean{
    return Random.nextInt(100) < random
}

fun convertMapToStringMap(map: Map<String, Any?>): Map<String, String>{
    return map.mapValues { (_, value) -> value.toString() }
}

fun MutableList<String>.randomInterval(player: Player, char: String = "#"): String {
    var sumRate = 0.0
    val position = this.contains("#")
    val pos = if (position) {
        1
    } else {
        0
    }

    forEach {
        if (position){
            sumRate += it.split(char)[pos].toDouble()
        } else {
            sumRate += 0
        }
    }

    val sortRates = mutableListOf<Double>()
    var tempSumRage = 0.0

    forEach {
        if (position) {
            tempSumRage += it.split(char)[pos].toDouble()
        } else {
            tempSumRage += 0
        }


        sortRates.add(tempSumRage / sumRate)
    }

    val nextDouble = Math.random()
    sortRates.add(nextDouble)
    sortRates.sort()

    return this[sortRates.indexOf(nextDouble)]
}


